package com.zy.ems.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public class RequestUtil {

    /**
     * 从request中获得参数Map，并返回可读的Map
     * 
     * @param request
     * @return
     */
    public static Map<String, String> getParameterMap(
            HttpServletRequest request) {
        // 参数Map
        Map<String, String[]> properties = request.getParameterMap();
        // 返回值Map
        Map<String, String> returnMap = new HashMap<String, String>();

        for (Entry<String, String[]> entry : properties.entrySet()) {
            String[] values = entry.getValue();
            String value = null;
            // 默认只有一个参数，只要同名参数的第一个
            if (values != null && values.length > 0) {
                value = StringUtils.trimToNull(values[0]);
            }
            if (StringUtils.isNotBlank(value)) {
                returnMap.put(entry.getKey(), value);
            }
        }

        return returnMap;
    }

    /**
     * 获取请求的真实客户端ip地址，nginx跳转后使用
     * 
     * @param request
     * @return
     */
    public static String getRealRemoteAddr(HttpServletRequest request) {
        return request.getHeader("X-Real-IP") != null
                ? request.getHeader("X-Real-IP") : request.getRemoteAddr();
    }
}
